<?php
namespace app\model;

use app\common\model\_Base;

class Role extends _Base
{
	/**
     * 保存数据
     * @param  obj $data 数据
     * @param  integer  $id 数据编号
     * @return bool       
     */
    public static function doSave($data,$id = '')
    {   
        $role = $id?Role::get($id):new Role;
        !empty($data['name']) && $role['name'] = $data['name'];
        isset($data['desc']) && $role->desc = $data['desc'];
        isset($data['sort']) && strlen($data['sort']) > 0 && $role->sort = $data['sort'];
        isset($data['status']) && strlen($data['status'])>0 && $role->status = $data['status'];
        !empty($data['permission']) && is_array($data['permission']) && $role->permission = serialize($data['permission']);
        if($id && isset($data['status']) && strlen($data['status']) > 0 && $data['status'] == 0 ){
        	$user = Admin::where(['role_id'=>$id])->find();
				if($user){
					return '该角色还有管理员在使用，无法禁用';
				}
        }
        $role->save();
        return false;
    }

	/**
	 * 删除数据 二次真实删除
	 * @param  integer $id 数据编号
	 * @return bool       
	 */
	public static function doDelete($id)
	{
		$role = Role::destroy($id);
        return false;
	}


	/**
	 * 获取数据
	 * @param  array    $cond  条件
	 * @param  string   $alias 条件表别名
	 * @param  integer  $page  页码
	 * @param  integer  $limit 每页条数
	 * @return array
	 */
	public static function doList($cond = [], $alias = false, $page = 1, $limit = 10, $order = 'sort asc')
	{   
		$total = Role::where($cond)->count();
		$list = Role::where($cond)->page($page,$limit)->order($order)->select();
		if(!$list->isEmpty()){
			$list->hidden(['permission'])
			->append(['status_text']);
		}
		return ['total' => $total,'list' => $list];
	}

	/**
	 * 获取详情
	 * @param  integer  $id  编号
	 * @return array
	 */
	public static function doDetail($id)
	{   
		$detail = Role::get($id)->append(['status_text']);
		$pii_ids = unserialize($detail->permission);
		$cond[] = ['status'=>self::STATUS_ENABLE];
		$list = Permission::doList()['list'];
		if(!empty($list)){
			foreach ($list as &$permission) {
				if($pii_ids && in_array($permission['id'], $pii_ids)){
					$permission['has']	= 1;
				}else{
					$permission['has'] 	= 0;
				}
			}
		}
		$detail->permission = $list;
		return $detail;
	}

	
}
